<!DOCTYPE html>
<html lang="en">

<!-- Head tag -->
<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="google-site-verification" content="xBT4GhYoi5qRD5tr338pgPM5OWHHIDR6mNg1a3euekI">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content>
    <meta name="keyword" content>
    <link rel="shortcut icon" href="/myblog/img/favicon.ico">

    <title>
        
          Heap对象 - Ethan的博客 | Ethan&#39;s Blog
        
    </title>

    <link rel="canonical" href="http://reflectyi.gitee.io/myblog/myblog/2016/10/01/jvm/memory/堆-对象创建-及其形态/">

    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/myblog/css/bootstrap.min.css">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/myblog/css/hux-blog.min.css">

    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/myblog/css/highlight.css">

    <!-- Custom Fonts -->
    <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <!-- Hux change font-awesome CDN to qiniu -->
    <link href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">


    <!-- Hux Delete, sad but pending in China
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/
    css'>
    -->


    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- ga & ba script hoook -->
    <script></script>
</head>


<!-- hack iOS CSS :active style -->
<body ontouchstart="">

    <!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
    <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/myblog/">Hi,Ethan</a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <!-- Known Issue, found by Hux:
            <nav>'s height woule be hold on by its content.
            so, when navbar scale out, the <nav> will cover tags.
            also mask any touch event of tags, unfortunately.
        -->
        <div id="huxblog_navbar">
            <div class="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li>
                        <a href="/myblog/">首页</a>
                    </li>

                    

                        
                    

                        
                        <li>
                            <a href="/myblog/about/">目录</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/myblog/archives/">时间轴</a>
                        </li>
                        
                    

                        
                        <li>
                            <a href="/myblog/tags/">标签</a>
                        </li>
                        
                    
                    
                </ul>
            </div>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>
<script>
    // Drop Bootstarp low-performance Navbar
    // Use customize navbar with high-quality material design animation
    // in high-perf jank-free CSS3 implementation
    var $body   = document.body;
    var $toggle = document.querySelector('.navbar-toggle');
    var $navbar = document.querySelector('#huxblog_navbar');
    var $collapse = document.querySelector('.navbar-collapse');

    $toggle.addEventListener('click', handleMagic)
    function handleMagic(e){
        if ($navbar.className.indexOf('in') > 0) {
        // CLOSE
            $navbar.className = " ";
            // wait until animation end.
            setTimeout(function(){
                // prevent frequently toggle
                if($navbar.className.indexOf('in') < 0) {
                    $collapse.style.height = "0px"
                }
            },400)
        }else{
        // OPEN
            $collapse.style.height = "auto"
            $navbar.className += " in";
        }
    }
</script>


    <!-- Main Content -->
    
<!-- Image to hack wechat -->
<!-- <img src="http://reflectyi.gitee.io/myblog/myblog/img/icon_wechat.png" width="0" height="0"> -->
<!-- <img src="{{ site.baseurl }}/{% if page.header-img %}{{ page.header-img }}{% else %}{{ site.header-img }}{% endif %}" width="0" height="0"> -->

<!-- Post Header -->
<style type="text/css">
    header.intro-header{
        background-image: url('/myblog/img/home-bg.jpg')
    }
</style>
<header class="intro-header" >
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <div class="post-heading">
                    <div class="tags">
                        
                          <a class="tag" href="/myblog/tags/#jvm" title="jvm">jvm</a>
                        
                          <a class="tag" href="/myblog/tags/#Memory" title="Memory">Memory</a>
                        
                    </div>
                    <h1>Heap对象</h1>
                    <h2 class="subheading">hotspot jvm对象创建</h2>
                    <span class="meta">
                        Posted by Ethan on
                        2016-10-01
                    </span>
                </div>
            </div>
        </div>
    </div>
</header>

<!-- Post Content -->
<article>
    <div class="container">
        <div class="row">

    <!-- Post Container -->
            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                post-container">

                <h2 id="hotspot虚拟机对象"><a href="#hotspot虚拟机对象" class="headerlink" title="hotspot虚拟机对象"></a>hotspot虚拟机对象</h2><h3 id="一、对象的创建"><a href="#一、对象的创建" class="headerlink" title="一、对象的创建"></a>一、对象的创建</h3><ul>
<li>概要：主要讨论堆中对象的创建，但是不包括数组和类对象。<h4 id="1、New指令发生了什么？"><a href="#1、New指令发生了什么？" class="headerlink" title="1、New指令发生了什么？"></a>1、New指令发生了什么？</h4></li>
<li><p>首先检测方法区常量池中，有没有class相关的引用，该class有没有加载相关的信息（被加载、解析、初始化）。如果没有加载，那么就加载class相关信息。</p>
<h5 id="1）、分配内存"><a href="#1）、分配内存" class="headerlink" title="1）、分配内存"></a>1）、分配内存</h5><ul>
<li><p>class加载完成后，会为为对象在新生代中，分配内存，分配内存根据GC回收算法不同采用的分配方式也不相同。</p>
<ul>
<li>serial和parNew等compact过程算法：<ul>
<li>指针碰撞，用过的内存放于一侧，没有用过的内存放于另一侧，中间放一个指针作为指示器。</li>
<li>因为这两种算法，都是基于标记–整理算法，会把堆内存空间整理成绝对规整的空间。</li>
<li>每次在创建对象的时候，只要把指针向空闲空间那边移动和对象大小相同的空间即可。</li>
</ul>
</li>
<li>CMS等Mark-sweep算法：<ul>
<li>空闲列表，记录哪块空间是可用的，并记录大小，为新对象分配内存</li>
<li>对象在内存中并不是规整的空间，而是使用过的空间和未使用的空间相互交错</li>
<li>cms采用的是吞吐最优，所以他没有整理空间。</li>
</ul>
</li>
</ul>
</li>
<li><p>多线程创建对象：</p>
<ul>
<li>A线程在创建对象时，移动指针，但是B对象同时也想拥有该空间，移动指针。那么这个指针本身本身不是线程安全的。两种方式：<ul>
<li>1、对内存空间同步处理：虚拟机使用CAS+失败重试机制，保证原子性。</li>
<li>2、预先给每个线程预先分配好一小块内存，称为本地线程分配缓冲（TLAB），当使用完TLAB以后，才需同步锁定。</li>
</ul>
</li>
</ul>
</li>
<li>虚拟机设置对象：<ul>
<li>设置Object Header:对象是哪个类的实例(类型指针)，对象的hash code，如何才能找到类的元数据，GC分代年龄信息。</li>
<li>已完成虚拟机对类和对象信息内容处理。</li>
<li>执行init方法，根据构造器，创建对象<h3 id="二、对象内存布局"><a href="#二、对象内存布局" class="headerlink" title="二、对象内存布局"></a>二、对象内存布局</h3></li>
</ul>
</li>
</ul>
</li>
<li>概述：对象在堆中：对象头（Header），实体数据(Intence Data)，还有对齐填充（Padding）<h4 id="1、对象头-Header"><a href="#1、对象头-Header" class="headerlink" title="1、对象头(Header)"></a>1、对象头(Header)</h4></li>
<li>对象运行时数据（Mark World）<ul>
<li>HashCode，GC年龄分代，锁状态标志，线程持有的锁，偏向线程ID和偏向时间戳等。</li>
<li>Mark World被设计成一个非固定的数据结构，不同的情况下，使用的内存大小是不同的，提高了内存利用率。</li>
</ul>
</li>
<li>class类型指针<ul>
<li>虚拟机通过这个指针标识这个对象是方法区中的哪个类的实例。</li>
<li>并不是所有的虚拟机实现都保留了class类型指针（句柄池），换句话说查找对象不一定通过对象本身。（hotspot是保留了类型指针的）</li>
</ul>
</li>
<li>java为数组类型<ul>
<li>对象头中必须保留数组长度的信息。</li>
<li>因为普通java对象可以通过元数据确定大小，但是数组不行。<h4 id="2、实例数据（Instance-Data）"><a href="#2、实例数据（Instance-Data）" class="headerlink" title="2、实例数据（Instance Data）"></a>2、实例数据（Instance Data）</h4></li>
</ul>
</li>
<li>保存对象的真正有用的信息，程序中定义的类型的字段信息（包括父类和自己的）。</li>
<li>字段的存储顺序会受到分配策略参数和字段在java源码中定义顺序影响<ul>
<li>hotspot默认参数分配策略：longs/doubles、ints、short/chars、bytes/booleans、oop(ordinary object Pinters) ,相同宽度的字段总是被分在一起。<h4 id="3、对齐填充"><a href="#3、对齐填充" class="headerlink" title="3、对齐填充"></a>3、对齐填充</h4></li>
</ul>
</li>
<li>并不是一定存在，对齐填充，仅仅是为了给对象占位。</li>
<li>hotspot要求对象占位必须是8byte的整数倍，对象头是8byte的整数倍，所以当Instance Data不是8的倍数的时候，就要padding补齐<h3 id="三、对象访问"><a href="#三、对象访问" class="headerlink" title="三、对象访问"></a>三、对象访问</h3></li>
<li>概要：虚拟机规范只是规定了，栈帧中局部变量表中的reference类型指向堆中对象，没有规定，该以何种方式去定位、访问这个对象。目前有两种方式，一种是句柄访问、一种是直接指针。（牵扯reference类型，对象实例，class类型）<h4 id="1、句柄访问（obj-header中就没放class类型指针）"><a href="#1、句柄访问（obj-header中就没放class类型指针）" class="headerlink" title="1、句柄访问（obj header中就没放class类型指针）"></a>1、句柄访问（obj header中就没放class类型指针）</h4></li>
<li>堆中划分出一块区域，作为句柄池。</li>
<li>栈帧局部变量表中reference保存的就是句柄池中对象的句柄地址。</li>
<li>句柄地址中，分别指向了obj实例数据和类型数据各自的具体地址。<h4 id="2、直接指针（hotspot）"><a href="#2、直接指针（hotspot）" class="headerlink" title="2、直接指针（hotspot）"></a>2、直接指针（hotspot）</h4></li>
<li>栈帧局部变量表中reference类型，保存的就是对象在堆中的具体地址</li>
<li>obj Header中类型指针直接指向了方法区中class类型</li>
</ul>


                <hr>

                

                <ul class="pager">
                    
                        <li class="previous">
                            <a href="/myblog/2016/10/01/jvm/memory/堆-内存分配和回收策略/" data-toggle="tooltip" data-placement="top" title="Heap中Obj分配策略和回收策略">&larr; Previous Post</a>
                        </li>
                    
                    
                        <li class="next">
                            <a href="/myblog/2016/10/01/jvm/memory/浅谈对象死亡-死亡判定(标记)/" data-toggle="tooltip" data-placement="top" title="浅谈对象死亡">Next Post &rarr;</a>
                        </li>
                    
                </ul>

                

                
                <!-- disqus 评论框 start -->
                <div class="comment">
                    <div id="disqus_thread" class="disqus-thread"></div>
                </div>
                <!-- disqus 评论框 end -->
                

            </div>
    <!-- Side Catalog Container -->
        
            <div class="
                col-lg-2 col-lg-offset-0
                visible-lg-block
                sidebar-container
                catalog-container">
                <div class="side-catalog">
                    <hr class="hidden-sm hidden-xs">
                    <h5>
                        <a class="catalog-toggle" href="#">CATALOG</a>
                    </h5>
                    <ul class="catalog-body"></ul>
                </div>
            </div>
        

    <!-- Sidebar Container -->

            <div class="
                col-lg-8 col-lg-offset-2
                col-md-10 col-md-offset-1
                sidebar-container">

                <!-- Featured Tags -->
                
                <section>
                    <!-- no hr -->
                    <h5><a href="/myblog/tags/">FEATURED TAGS</a></h5>
                    <div class="tags">
                       
                          <a class="tag" href="/myblog/tags/#jvm" title="jvm">jvm</a>
                        
                          <a class="tag" href="/myblog/tags/#Memory" title="Memory">Memory</a>
                        
                    </div>
                </section>
                

                <!-- Friends Blog -->
                
                <hr>
                <h5>FRIENDS</h5>
                <ul class="list-inline">

                    
                        <li><a href="http://blog.kaijun.rocks" target="_blank">Kaijun&#39;s Blog</a></li>
                    
                        <li><a href="http://huangxuan.me" target="_blank">Hux Blog</a></li>
                    
                        <li><a href="#" target="_blank">Foo</a></li>
                    
                        <li><a href="#" target="_blank">Bar</a></li>
                    
                        <li><a href="#" target="_blank">Example Friends</a></li>
                    
                        <li><a href="#" target="_blank">It helps SEO</a></li>
                    
                </ul>
                
            </div>

        </div>
    </div>
</article>




<!-- disqus 公共JS代码 start (一个网页只需插入一次) -->
<script type="text/javascript">
    /* * * CONFIGURATION VARIABLES * * */
    var disqus_shortname = "hexo-theme-huxblog";
    var disqus_identifier = "http://reflectyi.gitee.io/myblog/2016/10/01/jvm/memory/堆-对象创建-及其形态/";
    var disqus_url = "http://reflectyi.gitee.io/myblog/2016/10/01/jvm/memory/堆-对象创建-及其形态/";

    (function() {
        var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
        dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
</script>
<!-- disqus 公共JS代码 end -->




<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script>
    async("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js",function(){
        anchors.options = {
          visible: 'always',
          placement: 'right',
          icon: '#'
        };
        anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
    })
</script>
<style>
    /* place left on bigger screen */
    @media all and (min-width: 800px) {
        .anchorjs-link{
            position: absolute;
            left: -0.75em;
            font-size: 1.1em;
            margin-top : -0.1em;
        }
    }
</style>



    <!-- Footer -->
    <!-- Footer -->
<footer>
    <div class="container">
        <div class="row">
            <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
                <ul class="list-inline text-center">
                
                
                

                

                
                    <li>
                        <a target="_blank" href="https://www.facebook.com/stateInstance">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-facebook fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                
                    <li>
                        <a target="_blank"  href="https://github.com/stateInstance">
                            <span class="fa-stack fa-lg">
                                <i class="fa fa-circle fa-stack-2x"></i>
                                <i class="fa fa-github fa-stack-1x fa-inverse"></i>
                            </span>
                        </a>
                    </li>
                

                

                </ul>
                <p class="copyright text-muted">
                    Copyright &copy; Hi,Ethan 2019 
                    <br>
                    Theme by <a href="http://huangxuan.me">Hux</a> 
                    <span style="display: inline-block; margin: 0 5px;">
                        <i class="fa fa-heart"></i>
                    </span> 
                    Ported by <a href="http://blog.kaijun.rocks">Kaijun</a> | 
                    <iframe
                        style="margin-left: 2px; margin-bottom:-5px;"
                        frameborder="0" scrolling="0" width="91px" height="20px"
                        src="https://ghbtns.com/github-btn.html?user=kaijun&repo=hexo-theme-huxblog&type=star&count=true" >
                    </iframe>
                </p>
            </div>
        </div>
    </div>
</footer>

<!-- jQuery -->
<script src="/myblog/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="/myblog/js/bootstrap.min.js"></script>

<!-- Custom Theme JavaScript -->
<script src="/myblog/js/hux-blog.min.js"></script>


<!-- async load function -->
<script>
    function async(u, c) {
      var d = document, t = 'script',
          o = d.createElement(t),
          s = d.getElementsByTagName(t)[0];
      o.src = u;
      if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
      s.parentNode.insertBefore(o, s);
    }
</script>

<!-- 
     Because of the native support for backtick-style fenced code blocks 
     right within the Markdown is landed in Github Pages, 
     From V1.6, There is no need for Highlight.js, 
     so Huxblog drops it officially.

     - https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0  
     - https://help.github.com/articles/creating-and-highlighting-code-blocks/    
-->
<!--
    <script>
        async("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function(){
            hljs.initHighlightingOnLoad();
        })
    </script>
    <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet">
-->


<!-- jquery.tagcloud.js -->
<script>
    // only load tagcloud.js in tag.html
    if($('#tag_cloud').length !== 0){
        async("http://reflectyi.gitee.io/myblog/myblog/js/jquery.tagcloud.js",function(){
            $.fn.tagcloud.defaults = {
                //size: {start: 1, end: 1, unit: 'em'},
                color: {start: '#bbbbee', end: '#0085a1'},
            };
            $('#tag_cloud a').tagcloud();
        })
    }
</script>

<!--fastClick.js -->
<script>
    async("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function(){
        var $nav = document.querySelector("nav");
        if($nav) FastClick.attach($nav);
    })
</script>


<!-- Google Analytics -->


<script>
    // dynamic User by Hux
    var _gaId = 'UA-49627206-1';
    var _gaDomain = 'huangxuan.me';

    // Originial
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', _gaId, _gaDomain);
    ga('send', 'pageview');
</script>




<!-- Baidu Tongji -->

<script>
    // dynamic User by Hux
    var _baId = '4cc1f2d8f3067386cc5cdb626a202900';

    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<!-- Side Catalog -->

<script type="text/javascript">
    function generateCatalog (selector) {
        var P = $('div.post-container'),a,n,t,l,i,c;
        a = P.find('h1,h2,h3,h4,h5,h6');
        a.each(function () {
            n = $(this).prop('tagName').toLowerCase();
            i = "#"+$(this).prop('id');
            t = $(this).text();
            c = $('<a href="'+i+'" rel="nofollow">'+t+'</a>');
            l = $('<li class="'+n+'_nav"></li>').append(c);
            $(selector).append(l);
        });
        return true;    
    }

    generateCatalog(".catalog-body");

    // toggle side catalog
    $(".catalog-toggle").click((function(e){
        e.preventDefault();
        $('.side-catalog').toggleClass("fold")
    }))

    /*
     * Doc: https://github.com/davist11/jQuery-One-Page-Nav
     * Fork by Hux to support padding
     */
    async("/myblog/js/jquery.nav.js", function () {
        $('.catalog-body').onePageNav({
            currentClass: "active",
            changeHash: !1,
            easing: "swing",
            filter: "",
            scrollSpeed: 700,
            scrollOffset: 0,
            scrollThreshold: .2,
            begin: null,
            end: null,
            scrollChange: null,
            padding: 80
        });
    });
</script>





<!-- Image to hack wechat -->
<img src="http://reflectyi.gitee.io/myblog/myblog/img/icon_wechat.png" width="0" height="0" />
<!-- Migrate from head to bottom, no longer block render and still work -->

</body>

</html>
